package ch.ethz.fcl.metrobuzz.applications;

import java.io.File;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;

import ch.ethz.fcl.metrobuzz.MBContainer;
import ch.ethz.fcl.metrobuzz.MBProperty;
import ch.ethz.fcl.metrobuzz.controller.MBController;
import ch.ethz.fcl.metrobuzz.data.MBData;
import ch.ethz.fcl.metrobuzz.data.loader.plan.SingaporeTransitPlanFileLoader;
import ch.ethz.fcl.metrobuzz.render.MBRenderer;
import ch.ethz.fcl.metrobuzz.tools.MBTools;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer.ProjectionType;

public class InterchangeDemoApp {
	private int screenWidth = 7680;
	private int screenHeight = 4320;
	private MBContainer container;

	public static void main(String[] args) {
		if (args.length != 0)
			new InterchangeDemoApp(args).run();
		else {
			String res = "res/Singapore/roadnetwork";
			File folder = new File(res);
			if (!folder.exists())
				res = "Singapore/roadnetwork";
			String[] arguments = { res };
			new InterchangeDemoApp(arguments).run();
		}
	}

	public InterchangeDemoApp(String[] args) {
		init(args);
	}

	private void run() {
		while (!Display.isCloseRequested()) {
			GL11.glPushMatrix();
			container.getViewer().update();
			container.getRender().render();

			container.getControl().update();
			GL11.glPopMatrix();
			Display.update();
			Display.sync(32);
		}
		Display.destroy();
		System.exit(0);
	}

	private void init(String[] args) {
		if (args.length == 0) {
			System.out.println("please specify data base path on command line");
			System.exit(0);
		}

		MBProperty.read("properties/mrt_interchange_config.properties");

		container = new MBContainer();

		MBData data = new MBData(container);

		MBViewer view = new MBViewer(ProjectionType.Perspective, container);

		new SingaporeTransitPlanFileLoader().load(data, args[0]); // load data
		data.init();

		new MBRenderer(container);

		initDisplay();
		view.createDisplay(screenWidth, screenHeight, screenWidth, screenHeight,
				this.getClass().getSimpleName());
		view.getCamera().initDistance(0.8f);
		view.getCamera().disablePan();
		
		view.initFrame();

		new MBController(container);

		container.createFont();
	}

	private void initDisplay() {
		screenWidth = Display.getDesktopDisplayMode().getWidth();
		screenHeight = Display.getDesktopDisplayMode().getHeight();
		MBTools.debug(
				"Screen width " + screenWidth + " height " + screenHeight, true);
	}
}
